# -*- encoding: utf-8 -*-
from django.db import models
from datetime import datetime
from django.db.models import signals
#from utils.signals_comuns import slug_pre_save
from django.template.defaultfilters import slugify

class Album(models.Model):
    """ Album sera um pacote de imagens com o titulo e o slug para a identificacao  """
    class Meta:
        ordering = ('titulo',)
        
    titulo = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, blank=True, unique=True)
    imagem_capa = models.ImageField(null=True,blank=True,upload_to='fotos/galeria/capa')

    
    def __unicode__(self):
        return self.titulo
    
    
            
    
class Imagem(models.Model):
    """ Cada instancia contem uma imagem na galeria, thumbnail(miniatura) e imagem tamanh real  """
    class Meta:
        ordering = ('album', 'titulo',)
        
    album = models.ForeignKey('Album')
    titulo = models.CharField(max_length=100)
    slug = models.CharField(max_length=100, blank=True, unique=True)
    descricao = models.TextField(blank=True)
    original = models.ImageField(null=True,blank=True,upload_to='fotos/galeria/original')
    thumbnail = models.ImageField(null=True,blank=True,upload_to='fotos/galeria/thumbnail')
    
    def __unicode__(self):
        return self.titulo

def slug_pre_save(instance, sender, signal, *args, **kwargs):
    if not instance.slug:
        slug = slugify(instance.titulo)
        novo_slug = slug
        contador = 0
        
        while sender.objects.filter(slug=novo_slug).exclude(id=instance.id).count() > 0:
            contador +=1
            novo_slug = '%s-%d'%(slug, contador)
            
        instance.slug = novo_slug
        
signals.pre_save.connect(slug_pre_save, sender=Album)
signals.pre_save.connect(slug_pre_save, sender=Imagem)

